<template>

  <div>
    <el-container>
      <el-header>
          <span style="font-size: 30px;font-weight: bolder;">用户中心</span>
      </el-header>


      <el-main>

<!--        修改添加用户信息-->
        <el-drawer
            :title="dialogTitle"
            v-model="drawer"
            @close="handleClose">
          <el-form label-position="top">
            <el-form-item label="省/自治区">
              <el-input v-model="upRes.province"></el-input>
            </el-form-item>
            <el-form-item label="市">
              <el-input v-model="upRes.city"></el-input>
            </el-form-item>
            <el-form-item label="区">
              <el-input v-model="upRes.district"></el-input>
            </el-form-item>
            <el-form-item label="详细地址">
              <el-input v-model="upRes.detail_address"></el-input>
            </el-form-item>
            <el-form-item label="收货人">
              <el-input v-model="upRes.address_username"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="upRes.address_phone"></el-input>
            </el-form-item>
              <el-button link type="primary" size="small" @click="upAddress()">提交</el-button>
              <el-button link type="danger" size="small" @click="handleClose()">取消</el-button>
          </el-form>
        </el-drawer>



<!--        地址管理弹窗-->
        <el-dialog  :before-close="handleClose" :title="dialogTitle" v-model="dialogVis"  style="width:1000px;padding:40px;">
            <el-card>
              <el-button type="primary" @click="endAddDrawer()">添加地址</el-button>
              <el-table :data="userAddress">
                <el-table-column prop="province" label="省/自治区" align="center"></el-table-column>
                <el-table-column prop="city" label="市" align="center"></el-table-column>
                <el-table-column prop="district" label="区" align="center"></el-table-column>
                <el-table-column prop="detail_address" label="详细地址" align="center"></el-table-column>
                <el-table-column prop="address_phone" label="手机号" align="center"></el-table-column>
                <el-table-column prop="address_username" label="收货人" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <el-button link type="primary" size="small" @click="endDrawer(scope.row)">编辑</el-button>
                    <el-button link type="danger" size="small" @click="delDrawer(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
        </el-dialog>


<!--        用户信息修改弹窗-->
        <el-dialog :before-close="handleClose" :title="dialogTitle" v-model="dialogVisible"  style="width:1000px;padding:40px;">
            <el-form label-position="top">
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="密码">
                    <el-input placeholder="请输入密码" v-model="saveUser.password"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态">
                    <el-input placeholder="请输入状态" v-model="saveUser.status"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="金额">
                    <el-input placeholder="请输入金额" v-model="saveUser.money"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="昵称">
                    <el-input placeholder="请输入昵称" v-model="saveUser.nickname"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="手机号">
                    <el-input placeholder="请输入手机号" v-model="saveUser.phone"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          <template #footer>
            <el-button @click="handleClose()">取消</el-button>
            <el-button type="primary" @click="addUser()">确定</el-button>
          </template>
        </el-dialog>

        <el-card>
          <el-table :data="userArr"             
            v-loading="loading"
            element-loading-text="加载中..."
          >
            <el-table-column prop="username" label="用户名" align="center"></el-table-column>
            <el-table-column prop="status" label="状态" align="center"></el-table-column>
            <el-table-column prop="money" label="金额" align="center"></el-table-column>
            <el-table-column prop="nickname" label="昵称" align="center"></el-table-column>
            <el-table-column prop="phone" label="手机号" align="center" width="120px"></el-table-column>
            <el-table-column prop="avartar" label="头像" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="200px">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="editUser()">编辑</el-button>
                <el-button link type="danger" size="small" @click="userClose()">注销</el-button>
                <el-button link type="primary" size="small" @click="editAddress()">地址管理</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

      </el-main>
    </el-container>
  </div>

</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import {useUserStore} from "@/stores/index.js";
import {request} from "@/utils/request.js";
import { GetUserInfoAPI } from "@/apis/user";

//定义数组用来接收用户信息
const userArr = ref([]);
//控制弹窗是否显示
const dialogVisible = ref(false);
//定义变量控制dialog的标题
const dialogTitle = ref('修改用户信息');
//定义变量控制弹窗是否显示
const dialogVis = ref(false);
//定义变量存储用户地址信息
const userAddress = ref([]);
//定义变量控制dialog的弹窗是否显示
const drawer = ref(false);

// const id =ref("");
//定义对象用来接收弹窗用户地址信息
const upRes = ref({
  id: "",
  user_id: "",
  province: "",
  city: "",
  district:"",
  detail_address:"",
  address_phone:"",
  address_username:"",
});

const getData = async () => {
  const result = await request.get("/api/user/UserSelectServlet")
  console.log(result)
  userArr.value = [{...result}]

}

//定义对象用来接收弹窗用户信息
const saveUser = ref({
  password:"",status:"",money:"",nickname:"",address:"",phone:"",avartar:"",username:"",user_id:""
});

//定义添加用户方法

const userId = useUserStore().userInfo.token

const endAddDrawer = () => {
  drawer.value = true;
  dialogTitle.value = "用户地址添加";
  upRes.value = {
    province: "",
    city: "",
    district:"",
    detail_address:"",
    address_phone:"",
    address_username:"",
  };
  upRes.value = { ...upRes.value, user_id: userId }; // 只更新 user_id 字段
  console.log('Setting user_id for add address:', userId); // 调试输出
}

//定义函数用来删除用户地址
const delDrawer =(row) =>{
  let data = JSON.stringify(row.id);
  console.log(data);
  axios.get("/api/user/AddressDelServlet?id="+data,{
    headers:{
      "Authorization":row.user_id
    }
  })
      .then((response) =>{
        if (response.data.code === 1){
          ElMessage.success("删除成功");
          getData();
          editAddress();
        }else {
          ElMessage.error("删除失败");
        }
      })
}



const endDrawer = (row) =>{
  drawer.value = true;
  dialogTitle.value="用户地址更改";
  upRes.value= JSON.parse(JSON.stringify(row));
}

//地址修改
const upAddress = async () =>{
  let data = JSON.stringify(upRes.value);
  console.log(data);
  axios.post("/api/user/AddressAddServlet",data,{
    headers:{
      "Authorization":upRes.value.user_id
    }
  })
      .then((response) =>{
        if (response.data.code === 1){
          ElMessage.success("成功");
          getData();
        }else {
          ElMessage.error("失败");
        }
      })
}

//地址管理
const editAddress = () =>{
  dialogVis.value = true;
  dialogTitle.value="用户地址管理";
  axios.get("/api/user/AddressCheckServlet",{
    headers:{
      "Authorization": userId
    }
  })
      .then((response) =>{
        if (response.data.code === 1){
          userAddress.value = response.data.data;
          console.log(userAddress.value);
        }else {
          ElMessage.error("获取用户地址失败");
        }
      })

}


//用户注销
const userClose = () =>{
  axios.get("/api/user/UserLogoutServlet",{
    headers:{
      "Authorization": userId
    }
  })
      .then((response) => {
        if (response.data.code === 1){
          ElMessage.success("注销成功");
          localStorage.removeItem("user");
          router.push("/login");
        }else {
          ElMessage.error("注销失败");
        }
      })
}



//修改用户信息方法
const addUser = () =>{

  saveUser.value.username = userArr.value[0].username;
  let data = JSON.stringify(saveUser.value);
  console.log(data);
  //发送请求修改用户信息
  axios.post("/api/user/UserUpServlet",data,{
    headers:{
      "Authorization": userId
    },

  })
      .then(async (response) => {
        if (response.data.code === 1){
          ElMessage.success("修改用户信息成功");
          dialogVisible.value = false;
          const result = await GetUserInfoAPI()
          console.log("111");
          useUserStore().userInfo.money = result.money
          // location.reload()
          // getData();
        }else {
          ElMessage.error("修改用户信息失败");
        }
      })
}

//修改用户信息弹窗
const editUser = () =>{
  dialogVisible.value = true;
  dialogTitle.value="修改用户信息";
  // let userid = userArr.value[0].id;
  // id = userid;
  // console.log(userid);
  //发送请求获取用户信息
  axios.get("/api/user/UserSelectServlet",{
    headers:{
      "Authorization": userId
    }
  })
      .then((response) => {
        if (response.data.code === 1){
          saveUser.value = response.data.data;
        }else {
          ElMessage.error("获取用户信息失败");
        }
      })
}


const loading = ref(true)
//页面加载时加载用户信息
onMounted(async () =>{
  await getData()
  loading.value = false
})

//处理弹窗关闭的方法
const handleClose = () =>{
  // if (confirm("您确认要关闭本弹窗吗")){
  //   dialogVisible.value = false;
  //   dialogVis.value = false;
  //   drawer.value = false;
  // }
    dialogVisible.value = false;
    dialogVis.value = false;
    drawer.value = false;
}

</script>